package com.atguigu.chaptar8

import java.sql.{Connection, DriverManager, PreparedStatement}
import scala.util.Try

object $01_Exception {
  def main(args: Array[String]): Unit = {
    /*
        scala的异常处理:
            1.捕获异常
                1)try{..}catch{case e:Exception =>..}finally{} <一般只用于获取外部链接的场景,关闭资源>
                2)Try(可能异常的代码).getOrElse(默认值) <在处理数据时候经常使用>
                    Try的两个子类
                          Success:代表代码执行成功
                          Failture:代表代码执行失败
            2.抛出异常:throw抛出异常<一般不用>
              scala没有throws关键字(java里面这玩意一般也不用嘛)
     */
    //1.捕获异常在数据处理中的使用
    val list = List("zhangsan 20 3000", "lisi  5000", "zhaoliu 15 ")
    //需求:在数据格式不完整的情况下统计年龄,工资总和
    val result = list.map(x => {
      val arr = x.split(" ")
      //第一种捕获异常方式:这里一旦出现异常会模式匹配,而age需要Int值,所以传个0,麻烦,用第二种
      //1.1 val age = try{arr(1).toInt}catch {case e:Exception=>0}
          //val sal =try{arr(2).toInt}catch{case e:Exception=>0}
      val age = Try(arr(1).toInt).getOrElse(0)//1.2
      val sal =Try(arr(2).toInt).getOrElse(0)
      (age,sal)
      }).reduce((agg, curr) => {
      (agg._1 + curr._1, agg._2 + curr._2)
    })
    println(result)
  }
  //2.捕获异常在工作中的常用地方:关闭资源
  def jdbcMysql() = {
    var connection: Connection = null
    var statement: PreparedStatement = null
    try {
      connection = DriverManager.getConnection("jdbc:mysql://hadoop102:3306/test")
      statement = connection.prepareStatement("insert into person values(?)")
      statement.setString(1, "zhangsan")
      statement.executeUpdate()
    } catch {
      case e: Exception =>
    } finally {
      if (statement != null) {
        statement.close()
      }
      if (connection != null) {
        connection.close()
      }
    }
  }
    //1.捕获异常
    def m1(x: Int, y: Int) = {
      try {
        x / y
      } catch {
        case e: Exception => println("被除数为0")
      }

      //2.抛出异常 ( 工作中一般不用,谁会特意抛出异常终止程序进程啊 )
      def m2(x: Int, y: Int) = {
        if (y == 0) throw new Exception("被除数为0")
        x / y
      }




    }

}
